//
//  SYHomeViewController.m
//  BSHOUYIFANG
//
//  Created by 曹雁彬 on 15/8/13.
//  Copyright (c) 2015年 CYB. All rights reserved.
//

#import "SYHomeTableViewController.h"
#import "Header.h"
#import "MYRequestManger.h"
#import "SYHomeFTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "SYHSTableViewCell.h"
#import "SYHTTableViewCell.h"
#import "SYHFTableViewCell.h"
#import "SYButtonMoreTVC.h"
#import "SYDetailViewController.h"
#import "SYHttpTools.h"
typedef NS_ENUM(NSInteger, HaveNullArray)
{
    HaveNullArrayYes = 2,
    HaveNullArrayNo = 1,
};
@interface SYHomeTableViewController ()<UIScrollViewDelegate>
@property(nonatomic,strong)UIScrollView *sectionView;
@property(nonatomic,strong)UIPageControl *topPageControl;
@property(nonatomic,assign)NSInteger pageNumber;
@property(nonatomic,strong)NSMutableArray *dataSoure;
@property(nonatomic,assign)HaveNullArray haveNullArray;
@end

@implementation SYHomeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _haveNullArray = HaveNullArrayNo;
    self.navigationItem.title = @"首 页";
       self.navigationController.navigationBar.translucent = NO;
    // Do any additional setup after loading the view.
    
      [self postData];
   
    [self createScrollView];

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Home"];
    [self.tableView registerClass:[SYHomeFTableViewCell class] forCellReuseIdentifier:@"HomeF"];
    [self.tableView registerClass:[SYHSTableViewCell class] forCellReuseIdentifier:@"HomeFS"];
    [self.tableView registerClass:[SYHTTableViewCell class] forCellReuseIdentifier:@"HomeFT"];
     [self.tableView registerClass:[SYHFTableViewCell class] forCellReuseIdentifier:@"HomeFF"];

     [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(fistPageControl) userInfo:nil repeats:YES];
    
    
}

- (void)createScrollView
{
    if (_sectionView) {
        return;
    }
    _sectionView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/5+20)];
    _sectionView.contentSize = CGSizeMake(SCREEN_WIDTH*4, 0);
    _sectionView.contentOffset = CGPointMake(0, 0);
    _sectionView.delegate = self;
    _sectionView.pagingEnabled = YES;
    _sectionView.showsHorizontalScrollIndicator = NO;
    
    _topImageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/5+20)];
    _topImageView1.backgroundColor = [UIColor grayColor];
    _topImageView2 = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT/5+20)];
    _topImageView2.backgroundColor = [UIColor greenColor];
    _topImageView3 = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*2, 0, SCREEN_WIDTH, SCREEN_HEIGHT/5+20)];
    _topImageView3.backgroundColor = [UIColor redColor];
    _topImageView4 = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*3, 0, SCREEN_WIDTH, SCREEN_HEIGHT/5+20)];
    _topImageView4.backgroundColor = [UIColor blackColor];
    
    [_sectionView addSubview:_topImageView1];
    [_sectionView addSubview:_topImageView2];
//    [_sectionView addSubview:_topImageView3];
//    [_sectionView addSubview:_topImageView4];
    
    _textLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, SCREEN_HEIGHT/5-7, SCREEN_WIDTH-65, 20)];
    _textLabel.textColor = [UIColor whiteColor];
    _textLabel.backgroundColor = [UIColor colorWithRed:1/255.0 green:1/255.0 blue:1/255.0 alpha:0.01];
    _textLabel.font = [UIFont systemFontOfSize:15];
    
      // UIView *backgroud = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/5-11, SCREEN_WIDTH, 30)];
    // backgroud.backgroundColor = [UIColor colorWithRed:1/255.0 green:1/255.0 blue:1/255.0 alpha:0.06];
    // [self.tableView addSubview:backgroud];
    
    
    _topPageControl =[[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, 10, 10)];
    _topPageControl.center = CGPointMake(SCREEN_WIDTH-35, SCREEN_HEIGHT/5+3);
    //未选中的点的颜色
    //_topPageControl.backgroundColor = [UIColor blueColor];
    _topPageControl.pageIndicatorTintColor= [UIColor whiteColor];
    //选中的点的颜色
    _topPageControl.currentPageIndicatorTintColor= [UIColor redColor];
    _topPageControl.numberOfPages = 2;
    _topPageControl.currentPage = 0;
    _topPageControl.tag = 1501;
    // [pageControl addTarget:self action:@selector(numPage:) forControlEvents:UIControlEventValueChanged];
   
    
}
- (NSMutableArray *)dataSoure
{
    if (_dataSoure == nil) {
        self.dataSoure = [NSMutableArray array];
    }return _dataSoure;
}
- (void)postData
{
   SYHttpTools *manager = [SYHttpTools defaultManager];
    [manager get:@"http://sdxapp.com/api/geta.html?act=GetIndexData&mquan_id=556&F=android&V=1.4.0&key=1446771809103&channel=xiaomi&sign=0871971775ec11dbff77162d&user_id=&cid=0" success:^(id result) {
        NSArray *dic = result[@"data"];
                for (NSDictionary *dict1 in dic) {
                    SYHomeModel *model = [[SYHomeModel alloc]init];
                    [model setValuesForKeysWithDictionary:dict1];
                    if (model.data.count == 0) {
                        continue;
                    }
                    [self.dataSoure addObject:model];
                }
                [self.tableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"%@",error.description);
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    if (_dataSoure.count == 0) {
        return 0;
    }else
    {
        return self.dataSoure.count-1;

    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (self.dataSoure.count>0) {
        return 1;

    }else
    {
        return 0;
    }
}
- (void)createImage
{
    if (_dataSoure.count == 0) {
        return;
    }
    SYHomeModel *model =_dataSoure[0];
    if (model.data.count == 4) {
        [_topImageView3 sd_setImageWithURL:[NSURL URLWithString:model.data[2][@"img"]]];
        [_topImageView4 sd_setImageWithURL:[NSURL URLWithString:model.data[3][@"img"]]];
    }
    [_topImageView1 sd_setImageWithURL:[NSURL URLWithString:model.data[0][@"img"]]];
    
//    [_topImageView2 sd_setImageWithURL:[NSURL URLWithString:model.data[1][@"img"]]];
    
    
    [self.tableView addSubview:_textLabel];
    
    [self.tableView addSubview:_topPageControl];
    
    
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 7) {
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    footView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(35, footView.frame.size.height/2, 30, 1)];
        lineView.backgroundColor = [UIColor grayColor];
        [footView addSubview:lineView];
        
     UIView *lineView1 = [[UIView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-65, footView.frame.size.height/2, 30, 1)];
        lineView1.backgroundColor = [UIColor grayColor];
     [footView addSubview:lineView1];

        
    UILabel *footLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,footView.frame.size.height/2-10, SCREEN_WIDTH, 20)];
    footLabel.text = @"手工坊每天都有更新哦";
        footLabel.textColor = [UIColor grayColor];
        footLabel.font = [UIFont systemFontOfSize:15];
        footLabel.textAlignment = NSTextAlignmentCenter;
    [footView addSubview:footLabel];
    return footView;
    }else{
        
        return nil;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        [self createImage];

    return _sectionView;
    }else
    {
       UIView * sectionView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
        sectionView2.backgroundColor = [UIColor colorWithRed:247/255.0 green:239/255.0 blue:239/255.0 alpha:1.0];
        return sectionView2;
    }
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    UIPageControl *pageControl = (UIPageControl*)[self.tableView viewWithTag:1501];
    pageControl.currentPage = scrollView.contentOffset.x /SCREEN_WIDTH;
    _pageNumber = pageControl.currentPage;
}

- (void)fistPageControl
{
    UIPageControl *pageControl = (UIPageControl*)[self.tableView viewWithTag:1501];
    pageControl.currentPage = _pageNumber;
    
    UIScrollView *scrollview = _sectionView;
    if (_pageNumber != 0) {
        [UIView animateWithDuration:0.5 animations:^{
            scrollview.contentOffset =CGPointMake(pageControl.currentPage * SCREEN_WIDTH, 0);
        }];
    }else
    {
        scrollview.contentOffset =CGPointMake(pageControl.currentPage * SCREEN_WIDTH, 0);
    }
     SYHomeModel *model =_dataSoure[0];
     _textLabel.text = model.data[0][@"text"];
    _pageNumber++;
    if (_pageNumber == 2) {
        _pageNumber = 0;
    }
    // NSLog(@"%ld",_pageNumber);
    
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (indexPath.section) {
        case 0:
        {
            return SCREEN_HEIGHT/5+35;

        }
            break;
              case 1:
              case 7:
        {
            return SCREEN_HEIGHT/6*4;

        }
            break;
        case 4:
        case 2:
        case 3:
//        case 5:
//        case 6:
//        case 7:
//        case 8:
        {
             return (SCREEN_HEIGHT/6*4-25)/3*2+30;
        }
            break;
            break;
        default:
            return 0;
            break;
    }
    

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return SCREEN_HEIGHT/5+20;
    }else
    {
        return 5;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 7) {
        return 50;
    }
    return 0.1f;
}
//点击首页的 按钮 跳转到第二个视图控制器
- (void)goToSecondVC
{

    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //发送通知 携带参数
    NSNotification *notification = [[NSNotification alloc]initWithName:@"moonlight" object:nil userInfo:@{@"title":_str}];
    [center postNotification:notification];
      //跳转到到课堂
    self.tabBarController.selectedIndex = 1 ;

    //[self.navigationController pushViewController:momentsVC animated:YES];
    //[self presentViewController:momentsVC animated:YES completion:nil];
}
- (void)goToSecond
{
    self.tabBarController.selectedIndex = 1 ;
}
- (void)goToThirdVC
{
    SYButtonMoreTVC *buttonMore = [[SYButtonMoreTVC alloc]init];
    buttonMore.titleStr = _titleStr;
    [self.navigationController pushViewController:buttonMore animated:YES];
}
- (void)goToWebVC
{
     SYDetailViewController *detailVC = [[SYDetailViewController alloc]init];
   // NSLog(@"%@",_myID);
    detailVC.myID = _myID;
    detailVC.backupImg = _imageUrl;
    detailVC.backupTitle = _text;
    [self.navigationController pushViewController:detailVC animated:YES];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
        {
            SYHomeFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeF" forIndexPath:indexPath];
            SYHomeModel *model = self.dataSoure[1];
            
            cell.homeBlock = ^(NSString *str){
                _str = str;
                [self goToSecondVC];
              };
            
            cell.model = model;
            return cell;
        }
            break;
        case 1:
        {
            SYHSTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeFS" forIndexPath:indexPath];
            SYHomeModel *model = self.dataSoure[3];
            cell.shomeBlock = ^(NSString *title){
                _titleStr = title;
                [self goToThirdVC];
                
            };
            cell.homeWebBlock = ^(NSString *myID,NSString *imageUrl,NSString *title){
                _myID = myID;
                _imageUrl =imageUrl;
                _text = title;
                [self goToWebVC];
            };
            
            cell.model = model;
            return cell;
        }
            break;
        case 7:
        {
            SYHTTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeFT" forIndexPath:indexPath];
            SYHomeModel *model = self.dataSoure[7];
            cell.shomeBlock = ^(NSString *title){
                _titleStr = title;
                [self goToThirdVC];
            };
            cell.homeWebBlock = ^(NSString *myID,NSString *imageUrl,NSString *title){
                // NSLog(@"%@",myID);
                _myID = myID;
                _imageUrl = imageUrl;
                _text = title;
                [self goToSecond];
            };
            cell.model = model;
            return cell;
        }
            break;
        case 300:
        {
            SYHTTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeFT" forIndexPath:indexPath];
            SYHomeModel *model = self.dataSoure[indexPath.section+1];
             cell.shomeBlock = ^(NSString *title)
                {
                _titleStr = title;
                [self goToThirdVC];
               };
            cell.homeWebBlock = ^(NSString *myID,NSString *imageUrl,NSString *title){
                //   NSLog(@"%@",myID);
                _myID = myID;
                _imageUrl =imageUrl;
                _text = title;
                [self goToSecond];
            };
            cell.model = model;
            return cell;
        }
            break;
        case 4:
            case 2:
            case 3:
//        case 5:
//        case 6:
//        case 7:
//        case 8:
       // case 9:
        {
            SYHFTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeFF" forIndexPath:indexPath];
            
            SYHomeModel *model = _dataSoure[indexPath.section+_haveNullArray];
//            if (!model.data.count) {
//                model = self.dataSoure[indexPath.section+2];
//                cell.model = model;
//                _haveNullArray = HaveNullArrayYes;
//                return cell;
//                break;
//            }
            cell.shomeBlock = ^(NSString *title){
                _titleStr = title;
                [self goToThirdVC];
            };
            cell.homeWebBlock = ^(NSString *myID,NSString *imageUrl,NSString *title){
                //   NSLog(@"%@",myID);
                _myID = myID;
                _imageUrl =imageUrl;
                _text = title;
                [self goToWebVC];
            };
             cell.model = model;
            return cell;
        }
            break;
        
            
        default:
            break;
    }
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Home" forIndexPath:indexPath];
    return cell;


 }


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
